package pub.gll.onepeas.libbase.taskchain

import android.content.Context
import android.os.Bundle
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelStoreOwner
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.callbackFlow
import kotlinx.coroutines.launch
import pub.gll.onepeas.libbase.taskchain.JobTaskManager.jobMap
import pub.gll.onepeas.libbase.taskchain.SingleJob.Companion.JOB_AVAILABLE
import pub.gll.onepeas.libbase.taskchain.SingleJob.Companion.JOB_NOT_AVAILABLE

class Main {

    private var curLevel = 1
    private suspend fun doJob(context: Context, index: Int) {
        if (index > jobMap.size) return
        val singleJOb = jobMap[index]
        callbackFlow {
            if (singleJOb?.handle() == true) {
                singleJOb.launch(context) {
                    trySend(index + 1)
                }
            } else {
                trySend(index + 1)
            }
            awaitClose { }
        }.collect {
            curLevel = it
            judgeJob(context,it)
        }
    }
    private fun setTaskFlag(context:Context, level: Int, flag: Int, bundle: Bundle = Bundle()) {
        if (level > jobMap.size) {
            return
        }
        jobMap[level]?.apply {
            setStatus(flag)
            setBundle(bundle)
        }
        judgeJob(context,level)
    }
    /**
     * 应用启动就执行任务链
     */
    private fun loadTask(context: Context) {
        judgeJob(context, curLevel)
    }
    /**
     * 判断当前需要执行任务的优先级是否与curLevel一致，并且任务可执行
     */
    private fun judgeJob(context: Context, cur: Int) {
        val job = jobMap[cur]
        if(curLevel == cur && job?.status() != JOB_NOT_AVAILABLE){
            MainScope().launch {
                doJob(context, cur)
            }
        }
    }
    fun show(context: Context){

        val mainViewModel: MainViewModel by lazy {
            ViewModelProvider(context as ViewModelStoreOwner)[MainViewModel::class.java]
        }
        MainScope().launch {
            JobTaskManager.apply {
                loadTask(context)
                mainViewModel.firstApi.collect{
                    setTaskFlag(context, 1, JOB_AVAILABLE, Bundle().apply {
                        putString("dialog_type", it)
                    })
                }
                mainViewModel.secondApi.collect{
                    setTaskFlag(context, 2, JOB_AVAILABLE, Bundle().apply {
                        putString("dialog_type", it)
                    })
                }
                mainViewModel.thirdApi.collect{
                    setTaskFlag(context, 3, JOB_AVAILABLE, Bundle().apply {
                        putString("dialog_type", it)
                    })
                }
            }
        }
    }
}